<template>
  <div class="login-page">
    <div class="matrix-brand-section">
      <div class="matrix-brand-content">
        <!-- Logo区域 -->
        <div class="matrix-logo">
          <img src="/logo.png" alt="Matrix Framework Logo" />
          <h1 class="matrix-title">Matrix Framework</h1>
        </div>

        <!-- 标语描述 -->
        <p class="matrix-subtitle">企业级业务管理平台</p>

        <!-- 特性展示 -->
        <div class="matrix-features">
          <div class="matrix-feature">
            <div class="feature-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="feature-text">
              <h4>企业级安全</h4>
              <p>基于Keycloak的统一身份认证</p>
            </div>
          </div>

          <div class="matrix-feature">
            <div class="feature-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="feature-text">
              <h4>多租户支持</h4>
              <p>隔离的企业数据管理</p>
            </div>
          </div>

          <div class="matrix-feature">
            <div class="feature-icon">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="feature-text">
              <h4>统一认证</h4>
              <p>单点登录和权限管理</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧登录区域 -->
    <div class="matrix-login-section">
      <div class="matrix-login-card">
        <!-- 租户选择 -->
        <div class="tenant-selector" v-if="tenants.length > 1">
          <el-form-item label="选择租户">
            <el-select
              v-model="selectedTenant"
              placeholder="请选择租户"
              @change="onTenantChange"
              style="width: 100%"
            >
              <el-option
                v-for="tenant in tenants"
                :key="tenant.id"
                :label="tenant.displayName"
                :value="tenant"
              >
                <div class="tenant-option">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ tenant.displayName }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </div>

        <!-- 租户信息显示 -->
        <div class="matrix-tenant-info" v-if="selectedTenant">
          <div class="tenant-badge">
            <el-icon><OfficeBuilding /></el-icon>
            <span class="tenant-name">{{ selectedTenant.displayName }}</span>
          </div>
        </div>

        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          @submit.prevent="handleLogin"
          class="login-form"
        >
          <div class="login-header">
            <h2 class="login-title">欢迎回来</h2>
            <p class="login-subtitle">请使用您的Matrix Framework账号登录</p>
          </div>

          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名或邮箱"
              size="large"
              :prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              :prefix-icon="Lock"
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="loginForm.rememberMe">
              记住登录状态
            </el-checkbox>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              style="width: 100%"
              :loading="loading"
              @click="handleLogin"
            >
              <template v-if="!loading">
                <el-icon><Right /></el-icon>
                登录
              </template>
              <template v-else>
                登录中...
              </template>
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 其他登录方式 -->
        <div class="other-login">
          <el-divider>
            <span class="divider-text">或使用其他方式登录</span>
          </el-divider>

          <div class="social-login">
            <el-button
              v-if="supportsSocialLogin"
              type="success"
              plain
              size="large"
              @click="handleSocialLogin('wechat')"
            >
              <el-icon><ChatDotRound /></el-icon>
              微信登录
            </el-button>

            <el-button
              v-if="supportsSocialLogin"
              type="primary"
              plain
              size="large"
              @click="handleSocialLogin('dingtalk')"
            >
              <el-icon><Bell /></el-icon>
              钉钉登录
            </el-button>
          </div>
        </div>

        <!-- 底部链接 -->
        <div class="login-footer">
          <el-link
            type="primary"
            @click="showForgotPassword"
            :underline="false"
          >
            忘记密码？
          </el-link>
        </div>
      </div>

      <!-- 语言切换 -->
      <div class="language-selector">
        <el-dropdown @command="changeLanguage">
          <el-button text>
            <el-icon><Globe /></el-icon>
            {{ currentLanguage === 'zh' ? '中文' : 'English' }}
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="zh">中文</el-dropdown-item>
              <el-dropdown-item command="en">English</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="重置密码"
      width="400px"
    >
      <el-form :model="resetForm" :rules="resetRules">
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="resetForm.email"
            placeholder="请输入注册邮箱"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="forgotPasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">
          发送重置邮件
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import {
  User, Lock, Setting, OfficeBuilding, Right,
  Globe, ArrowDown, ChatDotRound, Bell
} from '@element-plus/icons-vue'
import authService from '@/services/AuthService'

interface Tenant {
  id: string
  name: string
  displayName: string
  keycloakRealm: string
  isActive: boolean
}

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tenants = ref<Tenant[]>([])
const selectedTenant = ref<Tenant | null>(null)
const currentLanguage = ref('zh')
const forgotPasswordVisible = ref(false)
const supportsSocialLogin = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 重置密码表单
const resetForm = reactive({
  email: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' },
    { min: 3, message: '用户名至少需要3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const resetRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 生命周期
onMounted(async () => {
  await loadTenants()
  checkRedirect()
})

// 方法
const loadTenants = async () => {
  try {
    // 模拟租户数据（实际应该从API获取）
    tenants.value = [
      {
        id: 'default-tenant',
        name: 'default-tenant',
        displayName: 'Matrix Framework',
        keycloakRealm: 'MatrixFramework',
        isActive: true
      }
    ]

    if (tenants.value.length === 1) {
      selectedTenant.value = tenants.value[0]
    }
  } catch (error) {
    console.error('加载租户列表失败:', error)
    ElMessage.error('加载租户列表失败')
  }
}

const checkRedirect = () => {
  const redirect = router.currentRoute.value.query.redirect as string
  if (redirect) {
    authService.pendingRedirect = redirect
  }
}

const onTenantChange = () => {
  console.log('租户变更:', selectedTenant.value?.displayName)
}

const handleLogin = async () => {
  if (!selectedTenant.value) {
    ElMessage.error('请选择租户')
    return
  }

  try {
    loading.value = true

    const result = await authService.login({
      username: loginForm.username,
      password: loginForm.password,
      tenantId: selectedTenant.value.id,
      rememberMe: loginForm.rememberMe
    })

    if (result.success) {
      ElMessage.success('登录成功！')

      // 跳转到目标页面
      const redirect = authService.pendingRedirect || '/dashboard'
      router.push(redirect)
      authService.pendingRedirect = ''
    } else {
      ElMessage.error(result.error || '登录失败')
    }
  } catch (error) {
    console.error('登录异常:', error)
    ElMessage.error('登录异常，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSocialLogin = (provider: string) => {
  ElMessage.info(`${provider} 登录功能开发中...`)
}

const changeLanguage = (lang: string) => {
  currentLanguage.value = lang
  ElMessage.success(`语言已切换为${lang === 'zh' ? '中文' : 'English'}`)
}

const showForgotPassword = () => {
  forgotPasswordVisible.value = true
}

const handleResetPassword = async () => {
  try {
    // 模拟发送重置邮件
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('重置邮件已发送，请查收')
    forgotPasswordVisible.value = false
  } catch (error) {
    ElMessage.error('发送重置邮件失败')
  }
}
</script>

<style scoped>
.login-page {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

/* 左侧品牌区域 */
.matrix-brand-section {
  flex: 1.2;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 3rem;
  color: white;
}

.matrix-brand-content {
  max-width: 500px;
  text-align: center;
}

.matrix-logo img {
  width: 120px;
  height: 120px;
  border-radius: 15px;
  margin-bottom: 1rem;
  background: white;
  padding: 1rem;
}

.matrix-title {
  font-size: 2.5rem;
  font-weight: 300;
  margin: 1rem 0;
  letter-spacing: -0.02em;
}

.matrix-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 3rem;
}

.matrix-features {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.matrix-feature {
  display: flex;
  align-items: center;
  gap: 1rem;
  text-align: left;
  animation: fadeInLeft 0.8s ease;
}

.feature-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
}

.feature-text h4 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 0.25rem 0;
  color: white;
}

.feature-text p {
  font-size: 0.9rem;
  margin: 0;
  opacity: 0.8;
  color: white;
}

/* 右侧登录区域 */
.matrix-login-section {
  flex: 0.8;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  background: white;
  position: relative;
}

.matrix-login-card {
  width: 100%;
  max-width: 420px;
}

.tenant-selector {
  margin-bottom: 1.5rem;
}

.tenant-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.matrix-tenant-info {
  margin-bottom: 2rem;
  text-align: center;
}

.tenant-badge {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  background: #f8f9fa;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  font-size: 0.9rem;
  color: #495057;
}

.tenant-badge .el-icon {
  color: #667eea;
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.login-title {
  font-size: 1.8rem;
  font-weight: 700;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.login-subtitle {
  font-size: 1rem;
  color: #666;
  margin: 0;
}

.other-login {
  margin-top: 1.5rem;
}

.divider-text {
  color: #999;
  font-size: 0.9rem;
}

.social-login {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.login-footer {
  text-align: center;
  margin-top: 1.5rem;
  padding-top: 1rem;
  border-top: 1px solid #e9ecef;
}

.language-selector {
  position: absolute;
  top: 1rem;
  right: 1rem;
}

/* 动画 */
@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-page {
    flex-direction: column;
  }

  .matrix-brand-section {
    flex: none;
    padding: 2rem;
  }

  .matrix-features {
    display: none;
  }

  .matrix-login-section {
    flex: 1;
    padding: 1rem;
  }
}
</style>